<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.building_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.building_delete"
                   @click="handleAdd">增 加
        </el-button>
      </template>

    </avue-crud>
     <!-- 回复 -->
    <el-dialog title="新 增"
                   append-to-body
                   :visible.sync="optionBoxShow"
                   width="70%">
    <avue-form ref="OptionForm" :data="data" :option="option" v-model="obj"  @submit="rowSave" @row-click="handleRowClick" >
      <template slot-scope="{row}" slot="input">
        <el-tag>{{row}}</el-tag>
      </template>
      <template slot="houseCheck" slot-scope="{dic}">
        <div style="float:left;width:100%;overflow:auto;height:100%;">
          <div id="obj_dic">{{dic}}</div>
          <div v-for="(unit,u_index) in obj.dic" :key="u_index">
            <el-card shadow="never" class="build_card">
              <div slot="header" class="clearfix">
                <span>{{unit.unitName}}</span>
              </div>
              <div class="text item" v-for="(level,l_index) in unit.child" :key="l_index">

                <el-checkbox v-for="aa in level" :checked="aa.checked" label="aa.label" :key="aa.label" @change="handleCheckChange">{{aa.label}}</el-checkbox>
              </div>
            </el-card>
          </div>
        </div>
      </template>
      <template slot-scope="{row}" slot="unitTotalHousehold">
        <div>{{(row.unitHousehold == undefined || row.unitFloorNumber  == undefined) ? '': row.unitHousehold*row.unitFloorNumber}}</div>
      </template>
      <template slot-scope="{row}" slot="households">
        <el-input v-model="households" placeholder="请输入住的人数" :disabled="true"></el-input>
      </template>
    </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/ninebasic/realpop/building";
  import {mapGetters} from "vuex";
  import { isvalidatemobile,cardid,validatenum} from "@/util/validate";

  //返回数据格式
  // var DIC = [
  //   {
  //     "unitName":'1单元',
  //     "unitIndex":1,
  //     "unitFloorNumber":3,
  //     "child":[
  //       [{"label":'101',"name":'101'},{"label":'102',"name":'102'},{"label":'103',"name":'103'}],
  //       [{"label":'201',"name":'201'},{"label":'202',"name":'202'},{"label":'203',"name":'203'}],
  //       [{"label":'301',"name":'301'},{"label":'302',"name":'302'},{"label":'303',"name":'303'}]
  //     ]
  //   },
  //   {
  //     "unitName":'2单元',
  //     "unitIndex":2,
  //     "unitFloorNumber":3,
  //     "child":[
  //       [{"label":'101',"name":'101'},{"label":'102',"name":'102'},{"label":'103',"name":'103'}],
  //       [{"label":'201',"name":'201'},{"label":'202',"name":'202'},{"label":'203',"name":'203'}],
  //       [{"label":'301',"name":'301'},{"label":'302',"name":'302'},{"label":'303',"name":'303'}]
  //     ]
  //   }
  // ]


  export default {
    data() {
       //手机号校验
      const validatePhone = (rule, value, callback) => {
        if (isvalidatemobile(value)[0]) {
          callback(new Error(isvalidatemobile(value)[1]));
        } else {
          callback();
        }
      };
      //校验身份正号码
      const validateCardid = (rule, value, callback) => {
        if(cardid(value)[0]){
          callback(new Error(cardid(value)[1]))
        }else{
          callback();
        }
      };
      //校验正整数
      const validateNum = (rule, value, callback) => {
        if(validatenum(value,1)){
          callback("请输入正整数")
        }else{
          callback();
        }
      };
      return {
        checkAll: false,
        isIndeterminate: true,

        form: {},
        query: {},
        households:'120',
        dic:[
            {
              "unitName":"1单元",
              "unitIndex":1,
              "unitFloorNumber":3,
              "child":[
                [{"label":"101","name":"101"},{"label":"102","name":"102"},{"label":"103","name":"103"}],
                [{"label":"201","name":"201"},{"label":"202","name":"202"},{"label":"203","name":"203"}],
                [{"label":"301","name":"301"},{"label":"302","name":"302"},{"label":"303","name":"303"}]
              ]
            },
            {
              "unitName":"2单元",
              "unitIndex":2,
              "unitFloorNumber":3,
              "child":[
                [{"label":"101","name":"101"},{"label":"102","name":"102"},{"label":"103","name":"103"}],
                [{"label":"201","name":"201"},{"label":"202","name":"202"},{"label":"203","name":"203"}],
                [{"label":"301","name":"301"},{"label":"302","name":"302"},{"label":"303","name":"303"}]
              ]
            }
          ],
        optionBoxShow:false,
        loading: true,
        obj: {
          buildingUnit: [
          ],
          dic:[
            {
              "unitName":"1单元",
              "unitIndex":1,
              "unitFloorNumber":3,
              "child":[
                [{"label":"101","name":"101"},{"label":"102","name":"102"},{"label":"103","name":"103"}],
                [{"label":"201","name":"201"},{"label":"202","name":"202"},{"label":"203","name":"203"}],
                [{"label":"301","name":"301"},{"label":"302","name":"302"},{"label":"303","name":"303"}]
              ]
            },
            {
              "unitName":"2单元",
              "unitIndex":2,
              "unitFloorNumber":3,
              "child":[
                [{"label":"101","name":"101"},{"label":"102","name":"102"},{"label":"103","name":"103"}],
                [{"label":"201","name":"201"},{"label":"202","name":"202"},{"label":"203","name":"203"}],
                [{"label":"301","name":"301"},{"label":"302","name":"302"},{"label":"303","name":"303"}]
              ]
            }
          ]
        },
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 30,
          dialogWidth: 1150,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          excelBtn: true,
          addBtn: false,
          dialogClickModal: false,
          saveBtn:false,
          updateBtn:false,
          column: [
             {
              label: "所属网格",
              prop: "gridId",
              type: "tree",
              span: 24,
              //multiple: true,
              parent: false,
              display: true,
              search: true,
              dicMethod: "get",
              dicUrl: "/api/smart-system/dept/tree",
              props: {
                label: "title"

              },
              rules: [{
                required: true,
                message: "请输入所属网格",
                trigger: "blur"
              }],
           },
            {
              label: "小区名称",
              prop: "communityName",
              type: "input",
              search: true,
              rules: [{
                required: true,
                message: "请输入小区名称",
                trigger: "blur"
              }],
            },
            {
              label: "楼栋名称",
              prop: "buildingName",
              type: "input",
              search: true,
              rules: [{
                required: true,
                message: "请输入楼栋名称",
                trigger: "blur"
              }],
            },
            {
              label: "楼栋面积",
              prop: "buildingArea",
              type: "input",
              hide: true,
            },
            // {
            //   label: "楼栋类型【商品房、自建房、别墅】",
            //   prop: "buildingType",
            //   type: "input",
            //   hide: true,
            // },
            {
              label: "楼栋层数",
              prop: "floorAmount",
              type: "input",
              rules: [{
                required: true,
                validator: validateNum,
                //message: "请输入楼栋层数",
                trigger: "blur"
              }],
              blur: ({value}) => {
                this.floorAmount = value

                //重新计算
                this.changeUnitFloorNumber(value)
              }
            },
            {
              label: "单元数",
              prop: "unitAmount",
              type: "input",
              rules: [{
                required: true,
                validator: validateNum,
                //message: "请输入单元数",
                trigger: "blur"
              }],
              blur: ({value}) => {

                this.addAll(value,this.floorAmount);
              }
            },
            {
            label: '单元信息',
            prop: 'buildingUnit',
            type: 'dynamic',
            span:24,
            children: {
              align: 'center',
              headerAlign: 'center',
              column: [
                {
                label: '单元名称',
                prop: "unitName",
                type: "input",
                disabled: false,
                 blur: ({value}) => {
                  this.indexInput  = value;
                },
                },
                {
                  label: '本单元楼层数',
                  prop: "unitFloorNumber",
                  type: 'number',

                },
                {
                  label: '本单元每层户数',
                  prop: "unitHousehold",
                  type: 'number',
                  blur: ({value}) => {
                   this.unitHousehold = value;
                  //  console.log(this.floorAmount);
                  this.unitTotalHousehold = value * this.floorAmount

                   this.changeObjFun(value,this.floorAmount,this.indexInput)
                  },
                },
                {
                  label: '本单元总户数',
                  prop: "unitTotalHousehold",
                  type: 'number',
                  formslot:true,
                  disabled:false,

                }
              ]
            }
          },
          {
            label:"标记不存在房屋",
            prop:'houseCheck',
            span:24,
            hide:true,
            formslot:true,
            dicData:this.dic,
            rules: [{
              required: true,
              message: "请输入姓名",
              trigger: "blur"
            }]
          },
          {
              label: "总户数",
              prop: "households",
              formslot:true,
              hide: true,
              // rules: [{
              //   required: true,
              //   validator: validateNum,
              //   //message: "请输入住的人数",
              //   trigger: "blur"
              // }],
            },
            {
              label: "住的人数",
              prop: "peopleAmount",
              type: "input",
              hide: true,
              rules: [{
                required: true,
                validator: validateNum,
                //message: "请输入住的人数",
                trigger: "blur"
              }],
            },
            {
              label: "经度",
              prop: "lng",
              type: "input",
              hide: true,
            },
            {
              label: "纬度",
              prop: "lat",
              type: "input",
              hide: true,
            },
            {
              label: "楼栋长姓名",
              prop: "buildingLeaderName",
              type: "input",
              search: true,
              rules: [{
                required: true,
                message: "请输入楼栋长姓名",
                trigger: "blur"
              }],
            },
            {
              label: "楼栋长身份证号",
              prop: "certNo",
              type: "input",
              hide: true,
              rules: [{
                required: true,
                validator: validateCardid,
                trigger: "blur"
              }],
              blur: ({value}) => {
                //this.$message.success(value,column)
                this.form.birthday  = value.substring(6,10)+"-"+value.substring(10,12)+"-"+value.substring(12,14);
                this.form.sex = value.substring(16,17)%2===0?'2':'1';
              }
            },
            {
              label: "性别",
              prop: "sex",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=sex",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请输入性别",
                trigger: "blur"
              }],
            },
            {
              label: "民族",
              prop: "nation",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=nation",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入民族",
                trigger: "blur"
              }],
            },
            {
              label: "政治面貌",
              prop: "pearty",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=party",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入政治面貌",
                trigger: "blur"
              }],
            },
             {
              label: "出生日期",
              prop: "birthday",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              hide: true,
              rules: [{
                required: true,
                message: "请输入出生日期",
                trigger: "blur"
              }],

            },
            {
              label: "学历",
              prop: "education",
              type: "select",
              dicUrl: "/api/smart-system/dict/dictionary?code=education",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              hide: true,
              rules: [{
                required: true,
                message: "请输入学历",
                trigger: "blur"
              }],
            },
            {
              label: "手机",
              prop: "mobile",
              type: "input",
              search: true,
              rules: [{
                required: true,
                validator: validatePhone,
               // message: "请输入手机",
                trigger: "blur"
              }],
            },
            {
              label: "固定电话",
              prop: "phone",
              type: "input",
              hide: true,
            },
            {
              label: "所在地",
              prop: "addr",
              type: "input",
              hide: true,
            },
            {
              label: "所在地详址",
              prop: "addrDetail",
              type: "input",
              hide: true,
              span: 24
            },
          ]
        },
        data: []
      };
    },
    watch:{
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.building_add, false),
          viewBtn: this.vaildData(this.permission.building_view, false),
          delBtn: this.vaildData(this.permission.building_delete, false),
          editBtn: this.vaildData(this.permission.building_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      //标记不存在房屋复选框事件
      handleCheckChange(val){
        if(val){
          this.households = this.households*1 + 1
        }else{
          this.households = this.households*1 - 1
        }

        this.form.households = this.households
      },

      //重新计算
      changeUnitFloorNumber(value){
        // let newObj = [];

        this.obj.buildingUnit.map((item,index)=>{
          this.obj.buildingUnit[index].unitFloorNumber = value
        })
      },

      //重新计算每层房屋数据
      changeDic(v){
        let newDic = []

        v.map(item=>{
          if(item.unitFloorNumber !== undefined && (typeof item.unitHousehold != "undefined")){

            let newDicUnit = {
              "unitName":item.unitName,
              "unitIndex":item.index,
              "unitFloorNumber":item.unitFloorNumber,
              "child":[]
            }

            let newLevel = []
            for(let i=1;i<=item.unitFloorNumber;i++){
              let newHouse = [];
              for(let j=1;j<=item.unitHousehold;j++){
                newHouse.push({'label':i+""+(j<9?"0"+j:j),'name':i+""+(j<9?"0"+j:j),'checked':false})
              }

              newLevel.push(newHouse)
            }
            newDicUnit.child = newLevel

            newDic.push(newDicUnit)
          }
        })

        console.log(JSON.stringify(newDic))

        this.dic = newDic
        // this.dic = this.dic
      },

      //本单元每层户数输入框失去焦点事件
      changeObjFun(unitHousehold,floorAmount,index){

        this.changeDic(this.obj.buildingUnit)

      },
      handleRowClick(row){
        console.log("我是click");
        this.$message({
          showClose: true,
          message: '序号' + row.$index,
          type: 'success',
        });
      },

      //单元数输入框失去焦点时
      addAll(unitAmount,floorAmount){
       // console.length(this.obj.dynamic.length());
       var jsonLength = 0;

        // for (let a in this.obj.buildingUnit) {
        //   aa = a
        //   jsonLength++;
        // }
        jsonLength = this.obj.buildingUnit.length
        this.obj.buildingUnit.splice(0,jsonLength);
        for(let i=1;i<=unitAmount;i++){
          let unitName = i+"单元";
          let unitFloorNumber = floorAmount;

          this.obj.buildingUnit.push({
            index: i,
            unitName: unitName,
            unitFloorNumber: unitFloorNumber,
            unitTotalHousehold:'',
            floorAmount:floorAmount,
            // unitHousehold:null,
            HouseCheck : null
          })
        }

        console.log("newbuildingunit:",this.obj.buildingUnit)

        this.changeDic(this.obj.buildingUnit)
      },
      handleAdd(){

          this.optionBoxShow = true
      },
      rowSave(row,done) {
         add(row).then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "保存成功!"
            });
               done();
            this.optionBoxShow = false;
            this.onLoad(this.page);
          }, error => {
           // loading();
            window.console.log(error);
          });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }

        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;

          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
.el-form-item__content{
   margin-left: 125px ! important;
}
.el-form-item__label {
  width: 125px ! important;
}
.build_card{float:left;margin-right:15px;}
</style>
